// 接口地址 
import log from "../utils/log"
import base64 from "./base64"

const hostApi = {
  apiForMoHe : 'https://service.essp.top/apiForMoHe',
  apiForBigScreen: 'https://service.essp.top/apiForBigScreen'
}
const imgApi = 'https://service.essp.top/mh/Image/'
const ForMoHe = (params, apiUrl='apiForMoHe') => {
  return new Promise((resolve, reject) => {
    let method = params.method || 'POST'
    let contentType = params.contentType || false
    const SUCCESS_STATUS = 200
    // console.log('---请求参数---', JSON.stringify(params.data))
    wx.request({
      url: hostApi[apiUrl] + params.url,
      method: method,
      data: params.data || {},
      header: {
        'content-type': contentType ? 'application/x-www-form-urlencoded' : 'application/json',
        "AccessToken": getApp().globalData.ACCESSTOKEN
      },
      success: res => {
        console.log(1, res)
        if (Object.is(res.statusCode, SUCCESS_STATUS)) {
          if (res.header.ACCESSTOKEN) {
            getApp().globalData.ACCESSTOKEN=res.header.ACCESSTOKEN
            wx.setStorageSync('ACCESSTOKEN', res.header.ACCESSTOKEN)
          }
          resolve(res.data)
        } else {
          log.error(res)
          resolve({data: res.data, statusCode: res.statusCode})
        }
      },
      fail: err => {
        log.error(err)
        console.log(err)
        wx.hideLoading()
        showError()
        reject(err)
      }
    })
  })
}
const http = (params, apiUrl='apiForBigScreen') => {
  return new Promise((resolve, reject) => {
    let method = params.method || 'POST'
    let contentType = params.contentType || false
    const SUCCESS_STATUS = 200
    console.log(getApp().globalData.ACCESSTOKEN,'token');
    // params.data.AppID = "wxa528b213925d2feb"
    console.log('---请求参数---', params.data)
    console.log(hostApi[apiUrl] + params.url);
    console.log(method);
    console.log(contentType);
    wx.request({
      url: hostApi[apiUrl] + params.url,
      method: method,
      data: params.data || {},
      header: {
        'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
      },
      success: res => {
        console.log(1, res)
        if (Object.is(res.statusCode, SUCCESS_STATUS)) {
          if (res.header.ACCESSTOKEN) {
            console.log(res.header.ACCESSTOKEN);
            getApp().globalData.ACCESSTOKEN=res.header.ACCESSTOKEN
            wx.setStorageSync('ACCESSTOKEN', res.header.ACCESSTOKEN)
          }
          resolve(res.data)
        } else {
          log.error(res)
          resolve({data: res.data, statusCode: res.statusCode})
        }
      },
      fail: err => {
        log.error(err)
        console.log(err)
        wx.hideLoading()
        showError()
        reject(err)
      }
    })
  })
}
function showError() {
  wx.showToast({
    title: '加载失败',
    icon: 'none',
    duration: 2000,
    mask: true
  })
}

module.exports = {
  http,
  ForMoHe,
  hostApi,
  imgApi
}